import { createAction, createReducer, ActionType, createAsyncAction } from 'typesafe-actions';
import { Dispatch } from 'redux';
import Axios from 'axios';
import produce from 'immer';
import { Dto, Item } from './dto';

export interface CapState {
    items: Item[]
    msg: string | null
    currentItem: Item | null
};

const changeActions = createAsyncAction(
    'CAP/CHANGE/REQUEST',
    ['CAP/CHANGE/SUCCESS', (res: Dto) => res],
    ['CAP/CHANGE/FAILURE', (err: Error) => err],
    'CAP/CHANGE/CANCEL',
)();



export type Actions = ActionType<typeof changeActions>
    ;

export const change = () =>
    async (dispatch: Dispatch) =>
        Axios.get<Dto>(`news`)
            .then(res => dispatch(changeActions.success(res.data)))
            .catch(error => {
                dispatch(changeActions.failure(error))
            })

const initialState: CapState = {
    msg: null,
    currentItem: null,
    items: []
};

export const Reducer = createReducer<CapState, Actions>(initialState)
    .handleAction(changeActions.success, (state, action) => produce(state, draft => {
        const item = action.payload.item
        draft.msg = action.payload.msg
        draft.currentItem = item
        if (item !== null) {
            console.log(state);
            const x = draft.items.findIndex(e => e.id === item.id)
            if (x === -1) {
                draft.items.push(item)
            } else {
                draft.items[x] = item
            }
        }
    }))


